import { urlWork } from 'nui';
import { d_sort, obj_str, is_empty, loc } from 'sui';

const get_type = (tp) => {
    const tmp = {
        "trigger": loc("mg_269"),
        "timer": loc("mg_270"),
        "alert": loc("cmd_7"),
        "call": loc("mg_281"),
    };

    return tmp[tp];
};

const build_it = (d) => {
    const ltp = get_type(d.tp);

    d["value"] = d.name;
    d["ltp"] = ltp;
    d["sub"] = `${ltp} ( ${d.uid} )`;
    d["state"] = d.active ? loc("jkqy") : loc("cmd_123");
};

const build_key = () => {
    const tmp = ["value", "ltp", "sub", "state", "index", "exp", "lv", "tableData"];
    const set = new Set();
    tmp.forEach(d => set.add(d));

    return set;
};

const load_id = (uid, hok, fnDone) => urlWork(fnDone, "cache/get", {uid: uid}, r => hok(r), e => hok(null));

const load_it = (hok) => {
    urlWork(null, "cache/list", {mod: "it"}, r => {
        const ret = [];

        r.forEach(d => {
            build_it(d);
            ret.push(d);
        });

        hok(ret);
    }, e => hok(null));
};

const build_tree = (plc, it) => {
    if (is_empty(it)) {
        return plc;
    }

    plc.forEach(d => {
        const id = d.id;
        const sub = it.filter(t => t.plc === id);
        sub.sort((a, b) => a.id > b.id);

        d["sub"] = sub;
    });

    return plc;
};

const plc_value = (d) => {
    return {
        uid: obj_str(d, "uid"),
        id: obj_str(d, "id"),
        value: obj_str(d, "name"),
        tp: "plc",
    };
};

const load_plc = (fnDone, hcmd) => {
    const hok = (v) => {
        if (fnDone) {
            fnDone();
        }

        hcmd(v);
    };

    urlWork(null, "cache/list", {mod: "plc"}, r => {
        const ret = [];

        r.forEach(d => {
            const t = plc_value(d);
            ret.push(t);
        });

        d_sort(ret, "value");

        load_it(tr => {
            const cmd = build_tree(ret, tr);
            hok(cmd);
        });
    }, e => hok(null));
};

const load_plc_id = (uid, hok) => urlWork(null, "cache/plc", {uid: uid},
    r => {
        r.forEach(d => build_it(d));

        r.sort((a, b) => a.id > b.id);

        r.forEach((d, i) => d["index"] = i + 1);

        hok(r);
    },
    e => hok(null));

export {plc_value, build_key, build_it, load_plc_id, load_id, load_plc};
